#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import sys
import subprocess
sys.path.append('/usr/lib64/fpemud-os-sysman')
from fm_util import Util


if sys.argv[1] == "init":
    subprocess.check_call(["modprobe", "zram"])
    out = subprocess.check_output(["zramctl", "-f"], text=True).rstrip("\n")
    assert out == "/dev/zram0"
    Util.writeFlagFile("/sys/block/zram0/disksize", Util.getInMemorySwapSizeInMb() * 1024 * 1024)
    subprocess.check_call(["mkswap", "/dev/zram0"])
    subprocess.check_call(["swapon", "/dev/zram0"])
    sys.exit(0)

if sys.argv[1] == "fini":
    # as a "close" action, ignore all errors
    if os.path.exists("/dev/zram0"):
        subprocess.run(["swapoff", "/dev/zram0"], stderr=subprocess.DEVNULL)
        subprocess.run(["zramctl", "-r", "/dev/zram0"], stderr=subprocess.DEVNULL)
    assert not os.path.exists("/dev/zram0")
    sys.exit(0)

assert False
